package com.nowcoder.controller;


import com.nowcoder.model.*;
import com.nowcoder.service.CommentService;
import com.nowcoder.service.NewsService;
import com.nowcoder.service.UserSevice;
import com.nowcoder.util.ToutiaoUtil;
import com.sun.deploy.net.HttpResponse;
import org.apache.struts.taglib.html.ImgTag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.swing.text.View;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class NewsController {
    private static final Logger logger = LoggerFactory.getLogger(NewsController.class);

    @Autowired
    NewsService newsService;

    @Autowired
    HostHolder hostHolder;

    @Autowired
    CommentService commentService;
    @Autowired
    UserSevice userSevice;

    @RequestMapping(value = {"/news/{newsId}"}, method = RequestMethod.GET)
    public String newsDatils(Model model, @PathVariable("newsId") String newsId) {
        try {
            int id = Integer.valueOf(newsId);
            News news = newsService.getById(id);
            if (news != null) {
                List<Comment> comments = commentService.getCommentByEntity(id, EntityType.ENTITY_NEWS);
                List<ViewObject> vos = new ArrayList<>();
                for (Comment comment : comments) {
                    ViewObject vo = new ViewObject();
                    vo.set("comment", comment);
                    vo.set("user", userSevice.getUser(comment.getUserId()));
                    vos.add(vo);
                }
                model.addAttribute("comments", vos);
            }
            model.addAttribute("news", news);
            model.addAttribute("owner", userSevice.getUser(news.getUserId()));
        } catch (Exception e) {
            logger.error("获得咨询详情错误", e.getMessage());
        }
        return "detail";
    }

    @RequestMapping(value = {"/addComment"},method = RequestMethod.POST)
    public String addComment(@RequestParam("newsId") int newsId,
                             @RequestParam("content") String content){
        Comment comment = new Comment();
        comment.setEntityId(newsId);
        comment.setContent(content);
        comment.setEntityType(EntityType.ENTITY_NEWS);
        comment.setUserId(hostHolder.getUser().getId());
        comment.setStatus(0);
        comment.setCreatedDate(new Date());
        commentService.addComment(comment);

        int count = commentService.addCommentCount(comment.getEntityId(),comment.getEntityType());
        newsService.updateCommentCount(comment.getEntityId(),count);

        return "redirect:/news/"+String.valueOf(newsId);
    }


    @RequestMapping(value = {"/image"}, method = RequestMethod.GET)
    @ResponseBody
    public void getImage(@RequestParam("name") String imageName,
                         HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");
            StreamUtils.copy(new FileInputStream(new File(ToutiaoUtil.IMAGE_DIR + imageName)), response.getOutputStream());
        } catch (Exception e) {
            logger.error("读取图片错误" + imageName + e.getMessage());
        }
    }

    @RequestMapping(value = {"/uploadImage/"}, method = RequestMethod.POST)
    @ResponseBody
    public String saveImage(@RequestParam("file") MultipartFile file) {
        try {
            String fileUrl = newsService.saveImages(file);
            if (fileUrl == null) {
                return ToutiaoUtil.getJSONString(1, "上传图片失败");
            }
            return ToutiaoUtil.getJSONString(0, fileUrl);
        } catch (Exception e) {
            logger.error("上传图片失败", e);
            return ToutiaoUtil.getJSONString(1, "上传失败");
        }
    }

    @RequestMapping(value = {"/user/addNews/"}, method = RequestMethod.POST)
    @ResponseBody
    public String addNews(@RequestParam("image") String image,
                          @RequestParam("title") String title,
                          @RequestParam("link") String link) {
        try {
            News news = new News();
            news.setCreatedDate(new Date());
            news.setTitle(title);
            news.setLink(link);
            news.setImage(image);
            if (hostHolder.getUser() != null) {
                news.setUserId(hostHolder.getUser().getId());
            } else {
                news.setUserId(3);
            }
            newsService.addNews(news);
            return ToutiaoUtil.getJSONString(0);
        } catch (Exception e) {
            logger.error("增加咨询失败", e.getMessage());
            return ToutiaoUtil.getJSONString(1, "发布失败");
        }
    }
}
